﻿using Infrastructure.Model.DI;
using Microsoft.Extensions.Logging;
using Model.CommonModel.PageModel;
using Model.EntityModel.Auth;
using Model.EntityModel.SysModel;
using Model.QueryModel.system;
using Repository.IRepository.ISysRepository;
using SqlSugar;

namespace Repository.Repository.SysRepository
{
    /// <summary>
    /// 组别
    /// </summary>
    [AppService(ServiceType = typeof(IGroupRepository), ServiceLifetime = LifeTime.Transient)]
    public class GroupRepository : SqlSugarBaseRepository<Group>, IGroupRepository
    {

        private readonly ILogger<GroupRepository> _logger;

        public GroupRepository( ILogger<GroupRepository> logger)
        {
  
            _logger = logger;
        }

        /// <summary>
        /// 获取所有有效组别
        /// </summary>
        /// <returns>组别列表</returns>
        public List<Group> GetActiveGroups()
        {
            try
            {
                return _db.Queryable<Group>()
                    .Where(g => g.IsActive == "Y")
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取有效组别失败");
                throw new Exception("获取有效组别时发生错误", ex);
            }
        }

        /// <summary>
        /// 根据ID列表获取组别
        /// </summary>
        /// <param name="ids">组别ID列表</param>
        /// <returns>组别列表</returns>
        public List<Group> GetGroupsByIds(List<string> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                    return new List<Group>();

                return _db.Queryable<Group>()
                    .Where(g => ids.Contains(g.Id))
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"根据ID列表获取组别失败，数量: {ids.Count}");
                throw new Exception("根据ID列表获取组别时发生错误", ex);
            }
        }

        /// <summary>
        /// 创建新组别
        /// </summary>
        /// <param name="group">组别实体</param>
        /// <returns>操作结果</returns>
        public bool CreateGroup(Group group)
        {
            try
            {
                // 设置创建时间
                group.CreatedAt = DateTime.Now;

                return _db.Insertable(group).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建组别失败，组名: {group.Name}");
                throw new Exception("创建组别时发生错误", ex);
            }
        }

        /// <summary>
        /// 更新组别信息
        /// </summary>
        /// <param name="group">组别实体</param>
        /// <returns>操作结果</returns>
        public bool UpdateGroup(Group group)
        {
            try
            {
                // 设置修改时间
                group.ModifiedAt = DateTime.Now;

                return _db.Updateable(group).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新组别失败，组别ID: {group.Id}");
                throw new Exception("更新组别信息时发生错误", ex);
            }
        }

        /// <summary>
        /// 更新组别状态
        /// </summary>
        /// <param name="groupId">组别ID</param>
        /// <param name="isActive">激活状态(Y/N)</param>
        /// <returns>操作结果</returns>
        public bool UpdateGroupStatus(string groupId, string isActive)
        {
            try
            {
                return _db.Updateable<Group>()
                    .SetColumns(g => new Group
                    {
                        IsActive = isActive,
                        ModifiedAt = DateTime.Now
                    })
                    .Where(g => g.Id == groupId)
                    .ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新组别状态失败，组别ID: {groupId}");
                throw new Exception("更新组别状态时发生错误", ex);
            }
        }

        /// <summary>
        /// 检查组别是否存在
        /// </summary>
        /// <param name="groupId">组别ID</param>
        /// <returns>是否存在</returns>
        public bool GroupExists(string groupId)
        {
            try
            {
                return _db.Queryable<Group>()
                    .Where(g => g.Id == groupId)
                    .Count() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查组别存在性失败，组别ID: {groupId}");
                throw new Exception("检查组别存在性时发生错误", ex);
            }
        }

        public Group GetGroupById(string groupId)
        {
            try
            {
                return _db.Queryable<Group>()
                    .Where(g => g.Id == groupId)
                    .First();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取组别信息失败，组别ID: {groupId}");
                throw new Exception("获取组别信息时发生错误", ex);
            }
        }
        public PagedInfo<Group> GetPageGroup(int pageNum, int pageSize, QueryGroup search)
        {
            int totalCount = 0;
            var queryable = _db.Queryable<Group>()
                .WhereIF(!string.IsNullOrWhiteSpace(search.Name), x => x.Name.Contains(search.Name))
                .WhereIF(!string.IsNullOrWhiteSpace(search.Category), x => x.Category == search.Category)
                .WhereIF(!string.IsNullOrWhiteSpace(search.IsActive), x => x.IsActive == search.IsActive);

            // 执行分页查询
            var pages = queryable.ToPageList(pageNum, pageSize, ref totalCount);
            var totalPages = (totalCount - 1) / pageSize + 1;

            return new PagedInfo<Group>
            {
                PageIndex = pageNum,
                PageSize = pageSize,
                TotalCount = totalCount,
                Data = pages,
                TotalPage = totalPages
            };
        }

        
    }
}

